class code5 {
    public int trap(int[] height) {
        int ret = 0;
        int n = height.length;
        int[] pre = new int[n];
        int preMax = 0;
        int[] suf = new int[n];
        int sufMax = 0;

        for(int i=0;i<n;i++) {
            preMax = Math.max(height[i],preMax);
            pre[i] = preMax;
        }

        for(int i = n-1;i>=0;i--) {
            sufMax = Math.max(height[i],sufMax);
            suf[i] = sufMax;
        }

        for(int i=0;i<n;i++) {
            ret += Math.min(pre[i],suf[i])-height[i];
        }

        return ret;
    }
}